import BaseControlService from "../base/service";
type Type = 'default' | 'attr';

abstract class BpmnControlService<T = unknown> extends BaseControlService {
  label: React.ReactNode;
  field?: string;
  /** attr的值存储需要 */
  type: Type;
  value?: T;

  constructor({ label, field, type }: { label: React.ReactNode, field?: string, type?: Type }) {
    super();
    this.label = label;
    this.field = field;
    this.type = type || 'default';
  }

  init(): void {
    const field = this.field;
    if (field) {
      if (this.type === 'attr') {
        this.value = this.panel.getElement().businessObject.$attrs?.[field];
      } else {
        this.value = this.panel.getElement().businessObject[field];
      }
    }
  }

  onChangeCallback?: (val: T) => void;

  bindOnChange(onChange?: (val: T) => void) {
    this.onChangeCallback = onChange;
  }

  onChange(val: T) {

    // 并不是真实的值
    this.value = val;

    if (this.onChangeCallback) {
      this.onChangeCallback(val);
    } else {
      this.updateProperties(val);
    }
  }

  updateProperties(val: T) {
    if (this.field) {
      this.root.getModeling().updateProperties(
        this.panel.getElement(),
        {
          [this.field]: val,
        },
      );
    }
  }

}

export default BpmnControlService;
